package com.nkzy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nkzy.exception.ServiceException;
import com.nkzy.mapper.DeptMapper;
import com.nkzy.models.TableData;
import com.nkzy.pojo.Dept;
import com.nkzy.models.PageQuery;
import com.nkzy.service.IDeptService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;


@Service
@RequiredArgsConstructor
public class DeptServiceImpl implements IDeptService {

    private final DeptMapper deptMapper;

    @Override
    public TableData<Dept> selectList(Dept dept, PageQuery pageQuery) {
        Page<Dept> depts = deptMapper.selectPage(pageQuery.build(), new LambdaQueryWrapper<Dept>()
                .like(StringUtils.hasText(dept.getName()), Dept::getName, dept.getName())
                .orderByDesc(Dept::getCreateTime));
        return TableData.build(depts);

    }

    @Override
    public Dept selectById(Long id) {
        return deptMapper.selectById(id);
    }

    @Override
    public void addDept(Dept dept) {
        var exists = deptMapper.exists(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getName, dept.getName()));
        if (exists) {
            throw new ServiceException("部门已存在");
        }
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.insert(dept);
    }

    @Override
    public void updateDept(Dept dept) {
        var entity = deptMapper.selectById(dept.getId());
        if (entity == null) {
            throw new ServiceException("部门不存在");
        }
        var exists = deptMapper.exists(new LambdaQueryWrapper<Dept>()
                .eq(Dept::getName, dept.getName())
                .ne(Dept::getId, dept.getId()));
        if (exists) {
            throw new ServiceException("部门已存在");
        }
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.updateById(dept);
    }

    @Override
    public void deleteDeptById(Long id) {
        var entity = deptMapper.selectById(id);
        if (entity == null) {
            throw new ServiceException("部门不存在");
        }
        deptMapper.deleteById(id);
    }
}
